﻿using Emgu.CV;
using Emgu.CV.Dnn;
using Microsoft.AspNetCore.Mvc;
using MyWatermark;
using NLog;
using System;
using System.ComponentModel.DataAnnotations;
using System.Net.Http.Headers;
using System.Runtime;
using System.Text.Json;
using WebApplication1.Models;
using WebApplication1.Services;
using LogLevel = NLog.LogLevel;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace WebApplication1.Controllers
{
    public class FileUploadRequest
    {
        [FromBody] // byte[] 作为请求体
        public byte[] FileBytes { get; set; }

        [FromQuery] // 字符串通过查询参数传递
        public string TextParam { get; set; }
    }

    [Route("api/[controller]")]
    [ApiController]
    public class WatermarkController : ControllerBase
    {
        private readonly ImageService _imageService;

        private static Logger _logger = NLog.LogManager.GetCurrentClassLogger();

        public WatermarkController(ImageService imageService)
        {
            _imageService = imageService;
        }

        //    [HttpPost("upload")]
        //    public async Task<IActionResult> Upload(IFormFile file)
        //    {
        //        try
        //        {
        //            var fileName = await _imageService.SaveImageAsync(file);
        //            return Ok(new
        //            {
        //                FileName = fileName,
        //                Url = Url.ActionLink("Download", "Images", new { fileName })
        //            });
        //        }
        //        catch (Exception ex)
        //        {
        //            return BadRequest(ex.Message);
        //        }
        //    }

        //    [HttpGet("download/{fileName}")]
        //    public IActionResult Download(string fileName)
        //    {
        //        var stream = _imageService.GetImageStream(fileName);
        //        if (stream == null) return NotFound();

        //        var contentType = GetContentType(fileName);
        //        return File(stream, contentType, fileName);
        //    }

        private static string GetContentType(string fileName)
        {
            var extension = Path.GetExtension(fileName).ToLowerInvariant();
            return extension switch
            {
                ".jpg" => "image/jpeg",
                ".jpeg" => "image/jpeg",
                ".png" => "image/png",
                ".gif" => "image/gif",
                _ => "application/octet-stream"
            };
        }


        //    [HttpGet("getWaterImages")]
        //    public async Task<IActionResult> GetFoldersAsync(
        //[FromQuery] int page = 1,
        //[FromQuery] int pageSize = 20)
        //    {
        //        var (folders, totalCount) = await _imageService.GetFoldersPagedAsync(page, pageSize);
        //        return Ok(new PagedResult<FolderInfo>
        //        {
        //            Page = page,
        //            PageSize = pageSize,
        //            TotalCount = totalCount,
        //            Items = folders
        //        });
        //    }


        //    [HttpGet("EmbedWaterTxt")]
        //    public async Task<IActionResult> EmbedWaterTxt(string fileName, string watermarkTxt = "asus")
        //    {
        //        var result = await _imageService.MakeWater(fileName, watermarkTxt);

        //        return Ok(new
        //        {
        //            result = result
        //        });
        //    }


        [HttpPost("Extract")]
        public async Task<IActionResult> Extract(IFormFile file)
        {
            var result = await _imageService.Extract(file);

            return Ok(new
            {
                result = result
            });
        }

        [HttpPost("uploadAndEmbed")]
        public IActionResult UploadAndEmbed(IFormFile file, [FromForm] string watermarkTxt = "asus")
        {
            try
            {


                (byte[] result, DebugInfo info) = _imageService.UploadAndEmbed(file, watermarkTxt).Result;

                if (result == null)
                {
                    return BadRequest("失败!");
                }

                var originalName = Path.GetFileNameWithoutExtension(file.FileName);
                var extension = Path.GetExtension(file.FileName).ToLowerInvariant();
                var contentType = GetContentType(file.FileName);



                var cd = new ContentDispositionHeaderValue("attachment")
                {
                    // 双重编码保障
                    FileName = Uri.EscapeDataString($"{originalName}_watermarked{extension}"),
                    FileNameStar = Uri.EscapeDataString($"{originalName}_watermarked{extension}")
                };

                Response.Headers.Add("Content-Disposition", cd.ToString());
                // 将调试信息序列化到响应头
                Response.Headers.Add("X-Debug-Info", JsonSerializer.Serialize(info));

                return File(result, contentType);

            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Error, ex.ToString());
                return BadRequest(ex.Message);
            }
        }

        [HttpPost("EmbedBytes")]
        public IActionResult EmbedBytes([FromBody] byte[] fileBytes, [FromQuery] string watermarkTxt)
        {
            _logger.Log(LogLevel.Error, $"EmbedBytes begin");
            byte[] result = null;
            try
            {
             

                (result, DebugInfo info) = _imageService.EmbedBytes(fileBytes, watermarkTxt).Result;

                var infoString = Newtonsoft.Json.JsonConvert.SerializeObject(info);
                _logger.Log(LogLevel.Error, $"EmbedBytes:length:{fileBytes.Length},waterma:{watermarkTxt} ,debug:{infoString}");

                //return result;
                return File(result, "application/octet-stream");

               
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Error, ex.ToString());
                return null;
            }
        }


        [HttpPost("ExtractString")]
        public async Task<string> ExtractString([FromBody] byte[] fileBytes)
        {
            try
            {
                _logger.Log(LogLevel.Error, $"ExtractString: length :{fileBytes.Length}");
                var result = WatermarkCore.BinaryToTextWithHeader(WatermarkCore.Extract(fileBytes));
                return result;
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Error, ex.ToString());
                return "";
            }
        }
        
        [HttpGet("Test")]
        public async Task<IActionResult> Test()
        {

            _logger.Log(LogLevel.Error, $"test");
            return Ok();

            var guid = Guid.NewGuid();
            string shortGuid = Convert.ToBase64String(guid.ToByteArray())
       .Replace("+", "-")
       .Replace("/", "_")
       .Substring(0, 22); // 移除末尾的填充符

            string apiUrl = $"https://localhost:7280/api/Watermark/EmbedBytes";
            //string apiUrl = $"http://dev-channel.wm.asus.com/api/Watermark/EmbedBytes";


            using (HttpClient _httpClient = new HttpClient())
            {
                byte[] fileBytes = System.IO.File.ReadAllBytes($@"D:\ywd\work\ncs\新水印的尝试\MyWatermark\gitee\pic\3.jpeg");
                string watermark = $"{111}_{222}_{DateTime.Now.Ticks}";
                byte[] result = null;
                apiUrl = $"{apiUrl}?watermarkTxt={Uri.EscapeDataString(watermark)}";
                try
                {
                    // 创建请求
                    using (var client = new HttpClient())
                    {
                        var content = new ByteArrayContent(fileBytes);

                        content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");


                        HttpResponseMessage response = await client.PostAsync(apiUrl, content);

                        // 读取响应
                        if (response.IsSuccessStatusCode)
                        {
                            byte[] responseBytes = await response.Content.ReadAsByteArrayAsync();
                            System.IO.File.WriteAllBytes($@"D:\ywd\work\ncs\新水印的尝试\MyWatermark\gitee\pic\3_api.jpeg",responseBytes);
                            return File(responseBytes,"image/jpeg");
                        }
                    }
                }
                catch (Exception ex)
                {

                }


            }
            return Ok();
        }
    }
}
